package com.alumni_circle.core.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alumni_circle.core.config.RedisCache;
import com.alumni_circle.core.entity.rbac.LoginUser;
import com.alumni_circle.core.security.PermissionDeniedHandler;
import com.alumni_circle.core.security.TokenInvalidHandler;
import com.alumni_circle.core.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 龙小虬
 * @since 2020-08-03 11:55
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private Logger logger = LoggerFactory.getLogger(getClass().getName());

    @Resource
    JwtUtils jwtUtils;

    @Resource
    RedisCache redisCache;

    @Resource
    TokenInvalidHandler tokenInvalidHandler;

    @Resource
    PermissionDeniedHandler permissionDeniedHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Access-Token");
        //判断token是否为空
        if(!StrUtil.isEmptyIfStr(token)){
            //解密token，并拿取到redis key
            Map map = jwtUtils.validateToken(token);
            //判断解密数据是否为空
            if(!ObjectUtil.hasEmpty(map)) {
                String key = map.get("key").toString();
                //判断Redis中是否存在此用户
                if(redisCache.hasKey(key)) {
                    //获取用户登录信息，判断是否拥有访问此url权限，有就重新登录用户并访问url
                    LoginUser loginUser = redisCache.getCacheObject(key);
                    String url = request.getRequestURI().substring(request.getContextPath().length());
                    logger.info("访问接口"+url);
                    System.out.println(url);
//                    chain.doFilter(request,response);
                    //判断此url是否在权限url中
//                    if (!ObjectUtil.hasEmpty(loginUser.getUrls()) && loginUser.getUrls().contains(url)) {
                        //刷新token
                        redisCache.updateCacheObject(key);
                        //验证
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                        chain.doFilter(request,response);
//                    }else {
//                        permissionDeniedHandler.handle(request,response,null);
//                    }
                }
            }else {
                tokenInvalidHandler.token(response);
            }
        }else {
            chain.doFilter(request, response);
        }
    }
}

